<?php
/**
 * 网站错误提示信息处理函数
 *
 * @access  private
 *
 * @param   string      $msg        提示语句,lang数组索引
 * @param   string      $gourl      提示跳转的地址
 * @param   int         $back       是否自动返回上个页面/默认不跳转
 *
 * @return  null
 */
function e($msg,$gourl='',$back=1)
{
	Message($msg,$back,$back);
}

/**
 * 网站成功提示信息处理函数
 *
 * @access  private
 *
 * @param   string      $msg        提示语句,lang数组索引
 * @param   string      $gourl      提示跳转的地址
 * @param   int         $back       是否自动返回上个页面/默认为自动跳转给出的url
 *
 * @return  null
 */
function s($msg,$gourl='',$back=0)
{
	Message($msg,$gourl,$back);
}

/**
 * 网站停止提示信息处理函数
 *
 * @access  private
 *
 * @param   string      $msg        提示语句,lang数组索引
 * @param   string      $gourl      提示跳转的地址
 * @param   int         $back       是否自动返回上个页面/默认为不显示跳转连接
 *
 * @return  null
 */
function stop($msg,$gourl='',$back=3)
{
	Message($msg,$gourl,$back);
}

/**
 * 网站提示信息处理函数
 *
 * @access  private
 *
 * @param   string      $msg        提示语句,lang数组索引
 * @param   string      $gourl      提示跳转的地址
 * @param   int         $back       是否自动返回上个页面
 *
 * @return  null
 */
function Message($msg,$gourl,$back)
{
	global $db;
	$jumptime = 2000;
	$htmlhead = '<html><head><title>提示信息</title><meta http-equiv="content-Type" content="text/html charset=utf-8" /><META HTTP-EQUIV="pragma" CONTENT="no-cache"><META HTTP-EQUIV="Cache-Control" CONTENT="no-cache, must-revalidate">';
	$htmlhead .= '<base target="_self"/></head><body leftmargin="0" topmargin="0" bgcolor="#FFFFFF"><center><script>';
	$htmlfoot  = '</script></center></body></html>';
	if(1==$back){
		$jumptime = 2000;
		$gourl = "javascript:history.go(-1);";
	}

	$func = "var pgo=0;function JumpUrl(){if(pgo==0) location='$gourl';pgo = 1;}";
	$rmsg = $func;
	$rmsg .= 'document.write(\'<div style="border:1px solid #FF8C00;width:550px;margin-top:25px;padding:1px;">\');';
	$rmsg .= 'document.write(\'<div style="height:20px;font-size:16px;font-weight:bold;BACKGROUND:#FF8C00;BORDER-BOTTOM:#FF8C00 2px solid;color:#FFFFFF;vertical-align:middle;padding:5px;">- 提示信息 -</div>\');';
	$rmsg .= 'document.write(\'<div style="height:100px;font-size:14px;"><br/>\');';

	$rmsg .= "document.write(\"$msg\");";
	if($back!=3)
	{
		$rmsg .= 'document.write(\'<br/><br/><a href="'.$gourl.'" style="font-size:12px;color:#336699;"><u>系统将在'.($jumptime/1000).'秒钟后自动跳转,如果你的浏览器没反应,请点击这里</u></a><br/><br/><div>\');';
	}
	$rmsg .= 'document.write("</div>");';
	if($back!=3)
	{
		$rmsg .= "setTimeout('JumpUrl()',$jumptime);";
	}
	$msg  = $htmlhead . $rmsg . $htmlfoot;
	echo $msg;
	if(is_object($db))
	{
		$db->close();
		unset($db);
	}
	ob_flush();
	exit();
}

/**
 * 无序随机码生成函数
 *
 * @access  public
 *
 * @param   int      	$length    	随机码长度
 * @param   int         $numeric	是否只为数字
 *
 * @return  string
 */
function random($length, $numeric = 0) {
	PHP_VERSION < '4.2.0' && mt_srand((double)microtime() * 1000000);
	if($numeric) {
		$hash = sprintf('%0'.$length.'d', mt_rand(0, pow(10, $length) - 1));
	} else {
		$hash = '';
		$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz';
		$max = strlen($chars) - 1;
		for($i = 0; $i < $length; $i++) {
			$hash .= $chars[mt_rand(0, $max)];
		}
	}
	return $hash;
}

/**
 * HTML表单hash码生成函数
 *
 * @access  public
 *
 * @return  string
 */
function formhash()
{
	global $localtime;
	if( isset($_SESSION[$GLOBALS['_CONFIG']['aprefix'].'username']) && isset($_SESSION[$GLOBALS['_CONFIG']['aprefix'].'uid']) ) {
		return substr(md5(substr($localtime, 0, -7).$GLOBALS['_CONFIG']['aprefix'].'username'.$GLOBALS['_CONFIG']['aprefix'].'uid'), 8, 8);
	}
}

/**
 * HTML表单POST提交安全检查函数
 *
 * @access  public
 *
 * @return  null
 */
function submitcheck()
{
	//检查是否为POST提交
	if($_SERVER['REQUEST_METHOD'] == 'POST' && $_POST['formhash'] != formhash())
	{
		stop('Sorry Your Submit Seccode Invalid!!');
	}
}
/**
 * 获取来访者IP
 * 
 * @return string
 */
function getIP()
{
	return isset($_SERVER["HTTP_X_FORWARDED_FOR"])?$_SERVER["HTTP_X_FORWARDED_FOR"]
						:(isset($_SERVER["HTTP_CLIENT_IP"])?$_SERVER["HTTP_CLIENT_IP"]
						:$_SERVER["REMOTE_ADDR"]);
}
/**
 * 文件上传处理函数
 *
 * @access  public
 *
 * @param   string      $filename      文件名称
 * @param   string      $tmpfile       临时文件名
 * @param   int			$filesize      文件大小
 * @param   string      $attach_dir    存放文件夹位置
 * @param   string      $uploadroot    上传文件夹根目录位置
 * @param   string      $uploadpath    上传文件夹目录
 *
 * @return  string
 */
function uploadfile($filename,$tmpfile,$filesize,$attach_dir='file',$uploadroot='',$uploadpath='')
{


	global $localtime;
    $extension  = strtolower(substr(strrchr($filename, "."),1));
	$filename   = $localtime.'.'.$extension;

    if (in_array($extension,$GLOBALS['_CONFIG']['upload_type']))
        die('public_common_file_type_error');
    //if($filesize>$attach_maxsize)
       // e('common_file_toolarge');
    //转移附件--按年月分类附件
	if($uploadroot=='')
		$uploadroot = 'upload/';
	if($uploadpath=='')
		$uploadpath = 'upload/'.date("Ym")."/";
    $attachpath = $uploadpath.$filename;
	if(file_exists($attachpath))
	{
		$attachpath=$uploadpath.$localtime.rand(1,1000).'.'.$extension;
	}
    if(!is_dir($uploadroot))
        @mkdir($uploadroot,0777) OR die("权限不足无法创建".$uploadroot."目录!请手动创建并设置权限为777");
    if(!is_dir($uploadpath))
        @mkdir($uploadpath,0777) OR die("创建".$uploadpath."目录失败");
    if(@is_uploaded_file($tmpfile)){
        if(!@move_uploaded_file($tmpfile ,$attachpath)){
                @unlink($tmpfile);//删除临时文件
                die('public_common_file_uploaderror');
        }
    }
    return $attachpath;
}
/**
 * js操作函数
 *
 * @access  public
 *
 * @param   string      $msg           jsr提示信息
 * @param   string      $url           跳转url
 * @param   int			$obj           窗口对象
 * @return  js
 */
function jsfun($msg='',$url='',$obj='')
{



	$M="<script language='javascript'>";


	 !empty($msg)?$M.="alert('".$msg."');":'';

	if($url!='')
	{
		if($obj!="")
		{

			$M.=$obj.".location.href='".$url."';";



		}else
		{

			$M.="location.href='".$url."';";

		}

	}

	$M.="</script>";

	echo $M;

	unset($M);



}


/**
 * 变量输出测试
 *
 * @access  public
 *
 * @return  chr
 */
function  A($v,$s='')
{

 	if(is_array($v))
 	{
 		echo '<pre>';
 			print_r($v);
 		echo '</pre>';


 	}else
 	{
 		echo $v;

 	}
	if($s==1)
	{
		exit;
	}
}

/**
 * 页面执行信息
 *
 * @access  public
 *
 * @return  chr
 */
function runinfo()
{
	global $db,$_CONFIG,$start_time;
   
	if($_CONFIG['isrun'])
	{

		
		$quernum  = $db->query_num;

		$db->close();

		unset($db);

		$end_time = array_sum(explode(' ',microtime()));// 程序运行信息

		$runtime  = number_format( $end_time - $start_time, 10);

		echo "\n<!--  $quernum times query, processed in $runtime second(s)  -->";

		ob_flush();


	}
	

}
 //写入文件
function swritefile($filename, $writetext, $openmod='wb') 
{
	if($fp = fopen($filename, $openmod)) {
		flock($fp, 2);
		//fwrite($fp,"\xEF\xBB\xBF");//设置成utf-8的文件
		fwrite($fp, $writetext);
		fclose($fp);
		return true;
	}
}
/**
 * Returns an array with the names of folders in a specific path
 * Will return 'error' (string) if there were an error with reading directory content.
 * Usage: 11
 *
 * @param	string		Path to list directories from
 * @return	array		Returns an array with the directory entries as values. If no path, the return value is nothing.
 */
function getDirs($path)	{
	if ($path)	{
		$d = dir($path);
		if (is_object($d))	{
			while(false !== ($entry=$d->read())) {
				if (@is_dir($path.'/'.$entry) && $entry!= '..' && $entry!= '.')	{
					$filearray[]=$entry;
				}
			}
			$d->close();
		} else return 'error';
		return $filearray;
	}
}
function delDirs($path) {
	$dh=opendir($path);
	while ($file=readdir($dh)) {
		if($file!="." && $file!="..") {
			$fullpath=$path."/".$file;
			if(!is_dir($fullpath)) {
				unlink($fullpath);
			} 
			else {
				delDirs($fullpath);
			}
		}
	}
	closedir($dh);
	if(rmdir($path)) {
		return true;
	}
	else {
		return false;
	}
}
/**
 * 		Returns an array with the names of files in a specific path
 *
 *      @param	string		$path: Is the path to the file
 * 		@param	boolean		If set, then the path is prepended the filenames. Otherwise only the filenames are returned in the array
 * 		@param	string		$order is sorting: 1= sort alphabetically, 'mtime' = sort by modification time.
 * 		@return	array		Array of the files found
 */
 function getFilesInDir($path,$prependPath=0,$order='')	{

		// Initialize variabels:
	$filearray = array();
	$sortarray = array();
	$path = rtrim($path, '/');

		// Find files+directories:
	if (@is_dir($path))	{
		$extensionList = strtolower($extensionList);
		$d = dir($path);
		if (is_object($d))	{
			while($entry=$d->read()) {
				if (@is_file($path.'/'.$entry))	{
					$fI = pathinfo($entry);
					$key = md5($path.'/'.$entry);	//md5 keyword
					$filearray[$key]=($prependPath?$path.'/':'').$entry;
					if ($order=='mtime') {$sortarray[$key]=filemtime($path.'/'.$entry);}
					elseif ($order)	{$sortarray[$key]=$entry;}
				}
			}
			$d->close();
		} else return 'error opening path: "'.$path.'"';
	}

		// Sort them:
	if ($order) {
		asort($sortarray);
		$newArr=array();
		foreach ($sortarray as $k => $v) {
			$newArr[$k]=$filearray[$k];
		}
		$filearray=$newArr;
	}

		// Return result
	reset($filearray);
	return $filearray;
}
/*
	写缓存
	最多二维数组
*/
function CreateConfigUre($d)
{
	$cachewrite = "<?php\n if(!defined('IN_SITE')) exit('Access Denied');\n";
        $cachewrite.= "\$CONFIGURE=array(\n";
        
        foreach($d as $key=>$v)
	{
		if(is_array($v))
		{
			
			$cachewrite.='"'.$key.'"=>array('."\n";
			foreach($v as $k=>$b)
			{
				$cachewrite.="\t\t".'"'.$k.'"=>"'.$b.'",'."\n";	
			}
			$cachewrite.="),\n";
		}else
		{
			$cachewrite.='"'.$key.'"=>"'.$v.'",'."\n";	
		}
	
	} 
       
        $cachewrite.=");\n";
        
        $cachewrite.="\n?>";
        
        swritefile(FILE_ROOT."include/data/configure.data.php",$cachewrite);
}
/*
	生成天气js缓存
*/
function WriteJsWeatherCache($weathercityno)
{
	include("include/class/Snoopy.class.php");
	$dir = FILE_ROOT."themes/default/javascript/weather.js";
	$url = "http://m.weather.com.cn/data/".$weathercityno.".html";
	$snoopy = new Snoopy;
	$result = $snoopy->fetch($url);
	if (strpos($result, "weatherinfo") !== false && strpos($result, "cityid") !== false) {
		swritefile($dir,"var __weather=$result;\n
		if (__weather.weatherinfo) __weather = __weather.weatherinfo;\n
		else __weather = {};\n
		var weatherdate='".date("Y-m-d H:i:s")."'".";");
	}
	
}
function WritePhpCache($filename,$array,$arrayname)//解析二维数组并写缓存
{
	
	$cachewrite = "<?php\n if(!defined('IN_SITE')) exit('Access Denied');\n";
        $cachewrite.= "\$".$arrayname."=array(\n";
        if(is_array($array))
	{
		foreach($array as $key=>$v)
	       {
		       if(is_array($v))
		       {
			       
			       $cachewrite.='"'.$key.'"=>array('."\n";
			       foreach($v as $k=>$b)
			       {
				       $cachewrite.="\t\t".'"'.$k.'"=>"'.$b.'",'."\n";	
			       }
			       $cachewrite.="),\n";
		       }else
		       {
			       $cachewrite.='"'.$key.'"=>"'.$v.'",'."\n";	
		       }
	       
	       } 
	}
       
       
        $cachewrite.=");\n";
        
        $cachewrite.="\n?>";
        
        swritefile($filename,$cachewrite);
}

function table($var)
{

	return $GLOBALS['_CONFIG']['db']['tablepre'].$var;
}
/**
 * 模块检查函数
 *
 * @access  public
 *
 * @return  chr
 */

	function module_is_exists()
	{
		$_path=$GLOBALS['_CONFIG']['module_home'].'/'.$GLOBALS['mod'];

		if(is_dir($_path))
		{
			return $_path;
		}else{
			e('模块驱动'.$_path.'不存在');
		}
	}

/**
 * 驱动检查函数
 *
 * @access  public
 *
 * @return  chr
 */

	function action_is_exists()
	{

		$_path = 'module/'.$GLOBALS['mod']."/".$GLOBALS['act'].'.inc.php';
		
		if(file_exists($_path))
		{
			return $_path;
		}else{
			
		    exit("<script language='javascript'>history.back();</script>");
			
			
		}
	}
	
	function action_is_globals()
	{
		
		$_path = 'module/'.$GLOBALS['mod'].'/_globals.php';
		
		if(file_exists($_path))
		{
			return $_path;
		}else{
			 exit("<script language='javascript'>history.back();</script>");
		}
	}
	
	function post($v)
	{
		if (!get_magic_quotes_gpc()) {
			return addslashes(htmlspecialchars(trim($_POST[$v])));
		}
		return addslashes(htmlspecialchars(trim(stripcslashes($_POST[$v]))));
	}
	function get($v)
	{
		if (!get_magic_quotes_gpc()) {
       		return addslashes(htmlspecialchars(trim($_GET[$v])));
       	}
       	return addslashes(htmlspecialchars(trim(stripcslashes($_GET[$v]))));
	}
       
	function msg($msg, $url='')
	{
       	$str = "<script type='text/javascript'>
       		self.parent.ShowAlert('$msg', '$url');
       	</script>";
       	die($str);       		
	}